package cn.slipi.core.plugin.pre;

import cn.slipi.common.constants.Constants;
import cn.slipi.common.entity.PdrApi;
import cn.slipi.common.entity.RequestLog;
import cn.slipi.common.enums.PluginDetailEnum;
import cn.slipi.common.rule.custom.entity.MatchCondition;
import cn.slipi.core.cache.ApiManager;
import cn.slipi.core.component.ratelimiter.RateLimiterFactory;
import cn.slipi.core.plugin.AbstractPlugin;
import cn.slipi.core.plugin.IPluginChain;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * RateLimiterPlugin
 */
public class RateLimiterPlugin extends AbstractPlugin {

    private static final Logger LOGGER = LoggerFactory.getLogger(SignPlugin.class);

    private final ApiManager apiManager;

    public RateLimiterPlugin(final ApiManager apiManager) {
        super(apiManager);
        this.apiManager = apiManager;
    }

    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, IPluginChain chain) {
        RequestLog requestLog = (RequestLog) exchange.getAttributes().get(Constants.REQUEST_LOG);

        MatchCondition requestCondition = (MatchCondition) exchange.getAttributes().get(Constants.GATEWAY_HEADER);
        PdrApi pdrApi = this.apiManager.getApiByCode(requestCondition.getApiCode());
        if (Objects.nonNull(pdrApi) && Objects.nonNull(pdrApi.getPermitsPerSecond())) {
            RateLimiter limiter = RateLimiterFactory.self().of(pdrApi.getPermitsPerSecond());
            if (limiter.tryAcquire(1, 10 * 1000, TimeUnit.SECONDS)) {
                LOGGER.debug("rate limiter pass");
            } else {
                requestLog.setRateLimiter("Too Many Requests");
                exchange.getAttributes().put(Constants.REQUEST_LOG, requestLog);
                return this.response(HttpStatus.TOO_MANY_REQUESTS);
            }
        }
        requestLog.setRateLimiter("ok");
        exchange.getAttributes().put(Constants.REQUEST_LOG, requestLog);
        return chain.execute(exchange);
    }

    @Override
    public String getPluginPhase() {
        return PluginDetailEnum.RATE_LIMITER.getPhase();
    }

    @Override
    public int getCode() {
        return PluginDetailEnum.RATE_LIMITER.getCode();
    }

    @Override
    public String getName() {
        return PluginDetailEnum.RATE_LIMITER.getName();
    }
}
